package NSA;

use strict;
use RT;
use RTx::AssetTracker::IP;

sub exceptions {

    my $struct = shift;
    my (%non_db_exceptions, %db_exceptions);

    foreach my $host ( keys %$struct ) {

        #Is it in the DB?
        my $ip = RTx::AssetTracker::IP->new($RT::SystemUser);
        my ($id, $msg) = $ip->Load($host);
        if ($id) {
            my $asset = $ip->AssetObj;
            # if up
            if ( $struct->{$host}->{state} eq 'up' ) {
                # do stuff if the ports changed
            }
            # if down
            else {
                $db_exceptions{$host}{category} = 'IP address not found during scan';
                $db_exceptions{$host}{object} = $asset;
            }
        }
        else {
            # if up
            if ( $struct->{$host}->{state} eq 'up' ) {
                # is it acting as a server?
                        if (
                                server_port(
                                @{ $struct->{$host}->{tcp}->{'open'} },
                                @{ $struct->{$host}->{udp}->{'open'} } )
                        )
                                {
                                        $non_db_exceptions{$host}{host} = $host;
                                        $non_db_exceptions{$host}{tcp} = $struct->{$host}{tcp}{'open'};
                                        $non_db_exceptions{$host}{udp} = $struct->{$host}{udp}{'open'};
                                        $non_db_exceptions{$host}{osguess} = $struct->{$host}{osmatch};
                                }
            }
            else {
                next;
            }
        }

    }

    return (\%non_db_exceptions, \%db_exceptions);

}

sub server_port {

    my @ports = @_;

    my @srv_ports = server_ports();

    foreach my $port (@srv_ports) {

        my $match = grep { $_ == $port } @ports;

        return 1 if ($match);

    }

    return 0;
}

sub server_ports {

    return ( 20, 21, 22, 23, 25, 53, 80, 109, 110, 111, 443, 515, 1433, 3306 );

}

sub offending_ports {

     my @offend;
     foreach my $srv ( server_ports() ) {

         push @offend, grep { $srv == $_ } @_;

     }

     return @offend;
}

1;
